/**
 * @Author: wangy
 * @Date: 2022-02-02 19:23:54
 * @LastEditTime: 2022-04-17 15:09:30
 * @Description: 
 * @Copyright (c) 2022 by wangy, All Rights Reserved. 
 */

// 封装优先级队列

export default class PriorityQueue {
	constructor() {
		this.items = [];
		this.element = "";
		this.priority = "";
	}

	// 封装构造函数
	queueElement(element, priority) {
		this.element = element;
		this.priority = priority;
	}

	// 判断队列是否为空
	isEmpty() {
		return this.items.length === 0;
	}

	// 添加元素的方法
	/******* 
	 * @description: 
	 * @param {*} element
	 * @param {*} priority
	 * @return {*}
	 */
	enqueue(element, priority) {
		// 1.根据传入的元素, 创建新的QueueElement
		let queueElement = new this.queueElement(element, priority);

		// 2.获取传入元素应该在正确的位置
		if (this.isEmpty()) {
			this.items.push(queueElement);
		} else {
			let added = false;
			for (let i = 0; i < this.items.length; i++) {
				if (queueElement.priority < this.items[i].priority) {
					this.items.splice(i, 0, queueElement);
					added = true;
					break;
				}
			}
			// 遍历完所有的元素, 优先级都大于新插入的元素时, 就插入到最后
			if (!added) {
				this.items.push(queueElement);
			}
		}
	}

	// 删除元素的方法
	dequeue() {
		return this.items.shift();
	}

	// 获取前端元素
	front() {
		return this.items[0];
	}

	// 获取元素的个数
	size() {
		return this.items.length;
	}

	// 以字符串形式输出队列
	toString() {
		let result = "";
		for (let item of this.items) {
			result += item.element + "-" + item.priority + " ";
		}
		return result;
	}
}
